<!-- 证照管理抽屉组件 -->
<template>
  <div>
    <a-drawer
      :title="drawerTitle"
      :width="drawerWidth"
      :visible="visible"
      :closable="true"
      @close="handleClose"
      placement="right"
      :destroyOnClose="true"
    >
      <div class="drawer-container">
        <!-- 搜索表单区域 -->
        <div class="search-form">
          <BasicForm @register="registerSearchForm" @submit="handleSearch" @reset="handleReset" />
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
          <BasicTable
            @register="registerTable"
            :dataSource="tableData"
            :loading="loading"
            size="small"
            :canResize="true"
            :bordered="true"
            :striped="true"
          >
            <template #toolbar>
              <a-button type="primary" @click="handleAddCertificate"> 新增证照 </a-button>
            </template>
            <template #action="{ record }">
              <TableAction :actions="getActions(record)" />
            </template>
            <template #isvalid="{ record }">
              <Tag :color="record.isvalid === true ? 'blue' : 'orange'">
                {{ record.isvalid === true ? '是' : '否' }}
              </Tag>
            </template>
          </BasicTable>
        </div>
      </div>
    </a-drawer>

    <!-- 新增/编辑证照表单模态框 -->
    <AddOrUpdateCertificateInfo
      @register="registerCertificateModal"
      @success="handleCertificateSuccess"
    />

    <!-- 附件查看模态框 -->
    <AttachmentModal @register="registerAttachmentModal" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, unref, watch, h } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { BasicTable, useTable, TableAction, BasicColumn } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Drawer, Modal, Tag } from 'ant-design-vue';
  // 这里需要替换为实际的API导入
  import {
    queryCertificateInfo,
    addCertificateInfo,
    updateCertificateInfo,
    deleteCertificateInfo,
  } from '/@/api/ehs/certificateInfo';
  import { certificateInfoDrawerTableColumns } from '/@/views/ehs/epiboly/epiboly.data';
  import AddOrUpdateCertificateInfo from '/@/views/ehs/certificateInfo/AddOrUpdateCertificateInfo.vue';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { useModal } from '/@/components/Modal';
  import AttachmentModal from '/@/views/ehs/certificateInfo/AttachmentModal.vue';

  // 注册证照编辑模态框
  const [registerCertificateModal, { openModal: openCertificateModal }] = useModal();

  const [registerAttachmentModal, { openModal: openAttachmentModal }] = useModal();
  // 注册证照编辑模态框
  export default defineComponent({
    name: 'CertificateManagementDrawer',
    components: {
      AttachmentModal,
      BasicForm,
      BasicTable,
      TableAction,
      Tag,
      'a-drawer': Drawer,
      'a-modal': Modal,
      AddOrUpdateCertificateInfo,
    },
    props: {
      // 控制抽屉显示
      visible: {
        type: Boolean,
        default: false,
      },
      // 来源类型: 'unit' 或 'person'
      type: {
        type: String,
        default: 'unit',
      },
      // 来源ID (unitid 或 personid)
      sourceId: {
        type: String,
        default: '',
      },
      // 来源名称 (unitname 或 personname)
      sourceName: {
        type: String,
        default: '',
      },
      // 预设查询条件
      fixedParams: {
        type: Object,
        default: () => ({}),
      },
      // 新增证照时的默认表单数据
      defaultFormData: {
        type: Object,
        default: () => ({}),
      },
      // 禁用的查询字段
      disabledQueryFields: {
        type: Array,
        default: () => [],
      },
      // 启用的查询字段
      enabledQueryFields: {
        type: Array,
        default: () => [],
      },
      // 组织代码
      orgcode: {
        type: String,
        default: '',
      },
    },
    emits: ['close', 'success'],
    setup(props, { emit }) {
      const { createMessage, createConfirm } = useMessage();

      // 抽屉配置
      const drawerWidth = ref('85%');
      const drawerTitle = computed(() => {
        const typeText = props.type === 'unit' ? '单位' : '人员';
        return `${props.sourceName || ''} - ${typeText}证照管理`;
      });

      // 表格数据和加载状态
      const tableData = ref([]);
      const loading = ref(false);



      // 搜索条件
      const searchParams = reactive({
        ...props.fixedParams,
        keywords: '',
        status: '',
      });

      // 搜索表单配置
      const searchFormSchemas: FormSchema[] = [
        {
          field: 'keywords',
          label: '关键字',
          component: 'Input',
          componentProps: {
            placeholder: '证照名称/编号',
            allowClear: true,
          },
          colProps: { span: 8 },
        },
        {
          field: 'status',
          label: '状态',
          component: 'Select',
          componentProps: {
            options: [
              { label: '全部', value: '' },
              { label: '有效', value: '1' },
              { label: '过期', value: '0' },
            ],
            allowClear: true,
          },
          colProps: { span: 8 },
        },
        {
          field: 'isepiboly',
          label: '相关方',
          component: 'Checkbox',
          defaultValue: true,
          show: false, // 隐藏但保持值
          colProps: { span: 8 },
        },
        {
          field: 'holdtype',
          label: '持有类型',
          component: 'RadioGroup',
          defaultValue: props.type === 'unit' ? '1' : '2',
          componentProps: {
            options: [
              { label: '单位证照', value: '1' },
              { label: '人员证照', value: '2' },
            ],
          },
          show: false, // 隐藏但保持值
          colProps: { span: 8 },
        },
        {
          field: 'epiboly',
          label: '持有人',
          component: 'Input',
          defaultValue: props.sourceId,
          show: false, // 隐藏但保持值
        },
      ];


      // 注册搜索表单
      const [registerSearchForm, { getFieldsValue: getSearchValues, setFieldsValue }] = useForm({
        schemas: searchFormSchemas,
        labelWidth: 80,
        baseColProps: { span: 8 },
        actionColOptions: {
          span: 8,
        },
        showSubmitButton: true,
        showResetButton: true,
        submitButtonOptions: {
          text: '查询',
        },
      });

      // 注册表格
      const [registerTable, { reload: reloadTable }] = useTable({
        title: '证照列表',
        columns: certificateInfoDrawerTableColumns,
        pagination: {
          pageSize: 10,
        },
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });

      // 获取表格操作列配置
      function getActions(record) {
        return [
          {
            icon: 'clarity:note-edit-line',
            tooltip: '编辑',
            onClick: () => handleEditCertificate(record),
          },
          {
            icon: 'ant-design:delete-outlined',
            tooltip: '删除',
            color: 'error',
            popConfirm: {
              title: '确定删除此证照?',
              confirm: () => handleDeleteCertificate(record),
            },
          },
          {
            icon: 'ant-design:eye-outlined',
            tooltip: '查看附件',
            onClick: () => handleViewAttachment(record),
          },
        ];
      }

      // 加载证照数据
      async function loadCertificateData() {
        if (!props.sourceId) return;

        loading.value = true;
        try {
          // 根据API文档构建参数
          const params: CertificateQueryConditionDto = {
            keywords: searchParams.keywords || '',
            status: searchParams.status || '',
            orgcode: props.orgcode,
            isepiboly: true, // 必填
            holdtype: props.type === 'unit' ? '1' : '2',
            epiboly: props.sourceId,
          };
          // 调用实际API
          const res = await queryCertificateInfo(params);
          tableData.value = res || [];
        } catch (error) {
          console.error('加载证照数据失败:', error);
          createMessage.error('加载证照数据失败');
          tableData.value = [];
        } finally {
          loading.value = false;
        }
      }

      // 处理搜索
      function handleSearch(values) {
        Object.assign(searchParams, values);
        loadCertificateData();
      }

      // 处理重置
      function handleReset() {
        // 重置搜索条件但保留固定参数
        Object.keys(searchParams).forEach((key) => {
          if (!Object.keys(props.fixedParams).includes(key)) {
            searchParams[key] = '';
          }
        });

        loadCertificateData();
      }

      // 关闭抽屉
      function handleClose() {
        emit('close');
      }

      // 新增证照
      function handleAddCertificate() {
        // 准备传给子组件的数据
        const modalData = {
          operateType: OperationTypeEnum.ADD,
          orgcode: props.orgcode,
          // 传递默认数据
          isepiboly: true,
          isperson: props.type === 'person',
          holduserid: props.sourceId,
          holdusername: props.sourceName,

          fromDrawer: true,
          drawerType: props.type,
        };
        // 打开证照编辑模态框
        openCertificateModal(true, modalData);
      }

      // 编辑证照
      function handleEditCertificate(record) {
        // 准备传给子组件的数据
        const modalData = {
          operateType: OperationTypeEnum.EDIT,
          id: record.id,
          orgcode: props.orgcode,

          // 编辑时也要传递抽屉的上下文信息
          fromDrawer: true,
          drawerType: props.type,
          sourceId: props.sourceId,
          sourceName: props.sourceName,
        };

        // 打开证照编辑模态框
        openCertificateModal(true, modalData);
      }

      // 处理证照操作成功
      function handleCertificateSuccess() {
        // 刷新数据
        loadCertificateData();
        // 通知父组件
        emit('success');
      }

      // 查看证照详情
      function handleViewAttachment(record) {
        // 实现查看详情逻辑
        createMessage.info('查看证照详情: ' + record.certificateName);
      }

      // 删除证照
      async function handleDeleteCertificate(record) {
        try {
          await deleteCertificateInfo(record.id);
          createMessage.success('删除成功');
          loadCertificateData();
        } catch (error) {
          console.error('删除证照失败:', error);
          createMessage.error('删除证照失败');
        }
      }




      // 设置禁用字段
      function setupDisabledFields() {
        if (props.disabledQueryFields && props.disabledQueryFields.length) {
          const updateSchemas = {};

          props.disabledQueryFields.forEach((field) => {
            updateSchemas[field] = {
              componentProps: {
                disabled: true,
              },
            };
          });

          // 应用禁用设置
          // 注意: 这里需要实现该功能或找到对应的API
        }
      }

      // 判断证照是否有附件
      function hasAttachment(record) {
        return (
          record.attachment &&
          record.attachment !== '' &&
          record.attachment !== '[]' &&
          record.attachment !== 'null'
        );
      }
      function handleViewAttachment(record) {

        if (!hasAttachment(record)) {
          createMessage.warning('该证照暂无附件信息');
          return;
        }

        // 打开附件查看模态框，传递证照记录
        openAttachmentModal(true, {
          record: record,
        });
      }

      // 监听抽屉显示状态
      watch(
        () => props.visible,
        (val) => {
          if (val) {
            setupDisabledFields();
            loadCertificateData();
          }
        },
        { immediate: true },
      );

      return {
        // 抽屉相关
        drawerWidth,
        drawerTitle,
        handleClose,

        // 表格相关
        registerTable,
        tableData,
        loading,
        getActions,

        // 搜索相关
        registerSearchForm,
        handleSearch,
        handleReset,

        // 模态框相关
        registerAttachmentModal,
        registerCertificateModal,

        // 操作方法
        handleAddCertificate,
        handleEditCertificate,
        handleDeleteCertificate,
        handleCertificateSuccess,
        handleViewAttachment,
      };
    },
  });
</script>

<style scoped lang="less">
  .drawer-container {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .search-form {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 4px;
  }

  .table-container {
    flex: 1;
    overflow: auto;
  }
</style>
